﻿using System;
using System.IO;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;
using System.Text.RegularExpressions;

[assembly: WebResource("Hxsoft.Web.UI.WebControls.UploadFileTypeValidator.UploadFileTypeValidator.js", "text/javascript", PerformSubstitution = true)]

namespace Hxsoft.Web.UI.WebControls
{
	/// <summary>
	/// 上传的文件类型验证。
	/// </summary>
	[ToolboxData("<{0}:UploadFileTypeValidator runat=server></{0}:UploadFileTypeValidator>")]
	public class UploadFileTypeValidator : BaseValidator
	{
		/// <summary>
		/// 允许上传的文件类型。
		/// </summary>
		[Browsable(true),
		Category("Behavior"),
		DefaultValue(null),
		Description("允许上传的文件类别。")]
		public string AllowUploadType
		{
			get
			{
				return (string)ViewState["AllowUploadType"];
			}
			set
			{
				ViewState["AllowUploadType"] = value;
			}
		}

		#region Override (重写)
		protected override void AddAttributesToRender(HtmlTextWriter writer)
		{
			base.AddAttributesToRender(writer);

			if (RenderUplevel)
			{
				writer.AddAttribute("evaluationfunction", "UploadFileTypeValidatorEvaluateIsValid", false);
				writer.AddAttribute("allowUploadType", AllowUploadType, true);
			}
		}

		protected override bool EvaluateIsValid()
		{
			// 获取控件值
			string controlValue = GetControlValidationValue(ControlToValidate);
			if (string.IsNullOrEmpty(controlValue))
				return true;

			// 获取文件类型
			string uploadType = GetFileType(controlValue);
			if (string.IsNullOrEmpty(uploadType))
				return false;

			bool isAllow = false;

			if (!string.IsNullOrEmpty(AllowUploadType))
			{
				if (Regex.IsMatch(uploadType, "^(" + AllowUploadType + ")$", RegexOptions.IgnoreCase))
					isAllow = true;
			}

			return isAllow;
		}

		protected override void OnPreRender(EventArgs e)
		{
			base.OnPreRender(e);

			if (RenderUplevel)
			{
				Type type = this.GetType();
				if (!Page.ClientScript.IsClientScriptIncludeRegistered(type, "UploadFileTypeValidator.js"))
				{
					string url = Page.ClientScript.GetWebResourceUrl(type, "Hxsoft.Web.UI.WebControls.UploadFileTypeValidator.UploadFileTypeValidator.js");
					Page.ClientScript.RegisterClientScriptInclude(type, "UploadFileTypeValidator.js", url);
				}
			}
		}
		#endregion


		/// <summary>
		/// 取得文件类型。
		/// </summary>
		/// <param name="fileName">文件的名称。</param>
		/// <returns>文件类型。</returns>
		public static string GetFileType(string fileName)
		{
			if (string.IsNullOrEmpty(fileName))
				return null;

			int position = fileName.LastIndexOf('.');
			if (position == -1)
				return null;
			return fileName.Substring(position + 1);
		}
	}
}